package com.niuzi.servlet;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;

@WebServlet(urlPatterns = "/code")
public class CodeServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        int width = 60;
        int height = 40;

        BufferedImage image = new BufferedImage(width , height , BufferedImage.TYPE_INT_RGB);

        Graphics graphics = image.getGraphics();

        graphics.setColor(Color.BLUE);

        graphics.fillRect(0,0,width,height);

        String code = createCode();

        req.getSession().setAttribute("code" , code);
        req.getSession().setAttribute("code_create_time" , System.currentTimeMillis());

        graphics.setColor(Color.GRAY);

        graphics.setFont(new Font("微软雅黑" , Font.BOLD , 20));
        graphics.drawString(code , (int) (width*0.1) , (int)(height*0.7));

        graphics.setColor(Color.cyan);
        for (int i = 0; i < 10; i++) {
            graphics.drawLine((int)(Math.random()*width), (int)(Math.random()*height), (int)(Math.random()*width), (int)(Math.random()*height));
        }

        ImageIO.write(image , "jpg" , resp.getOutputStream());
    }

    private String createCode() {
        return  (int)(Math.random() * 9000 + 1000) + "";
    }
}
